import printTemplateService, { type PageListReq } from "@/api/services/tool/printTemplateService";
import CustomTable from "@/components/grid/CustomTable";
import TableDictTag from "@/components/grid/TableDictTag";
import { Upload } from "@/components/upload";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import SingleCustomerSelector from "@/pages/components/selector/SingleCustomerSelect";
import SingleMaterialSelector from "@/pages/components/selector/SingleMaterialSelect";
import { ExportOutlined, UserAddOutlined } from "@ant-design/icons";
import { Button, Card, Drawer, Form, Input, Select, Space, Spin, Switch, Upload as AntdUpload } from "antd";
import type { ColumnsType } from "antd/es/table";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import type { PrintResponse, PrintTemplate } from "./entity";
import { useNavigate } from "react-router";
import { el } from "@faker-js/faker";

export default function PrintTemplatePage() {
	const navigate = useNavigate();

	const [loading, setLoading] = useState(false);
	const [submitLoading, setSubmitLoading] = useState(false);
	const [submitTip, setSubmitTip] = useState("数据提交中...");
	const [queryParams, setQueryParams] = useState<PageListReq>({
		name: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<PrintTemplate[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<PrintTemplate | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	const [customerSelectVisible, setCustomerSelectVisible] = useState(false);
	const [selectMaterialVisiable, setSelectMaterialVisiable] = useState(false);

	const [fileList, setFileList] = useState<UploadFile[]>([]);

	const [dataSourceList, setDataSourceList] = useState([]);

	const typeOptions = useDictionary("print_template_type");

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	useEffect(() => {
		getDataSource();
	}, []);

	const columns: ColumnsType<PrintTemplate> = [
		{
			title: "名称",
			width: 120,
			key: "name",
			dataIndex: "name",
		},
		{
			title: "模板类型",
			width: 120,
			key: "type",
			dataIndex: "type",
			render: (_, record) => <TableDictTag dictCode="print_template_type" value={record.type ?? ""} />,
		},
		{
			title: "物料编码",
			width: 120,
			key: "materialCode",
			dataIndex: "materialCode",
		},
		{
			title: "物料名称",
			width: 120,
			key: "materialName",
			dataIndex: "materialName",
		},
		{
			title: "客户",
			width: 120,
			key: "clientName",
			dataIndex: "clientName",
		},
		{
			title: "模板文件名称",
			width: 120,
			key: "templateFileName",
			dataIndex: "templateFileName",
		},
		{
			title: "是否默认",
			width: 120,
			key: "isDefault",
			dataIndex: "isDefault",
			render: (_, record) => <TableDictTag dictCode="system_true_false" value={record.isDefault ?? ""} />,
		},
		{
			title: "启用状态",
			width: 120,
			key: "enableFlag",
			dataIndex: "enableFlag",
			render: (_, record) => <TableDictTag dictCode="system_status" value={record.enableFlag ?? ""} />,
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 180,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
					<Button type="link" onClick={() => handleDesign(record)}>
						设计
					</Button>
				</Space>
			),
		},
	];

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		printTemplateService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// 获取数据源
	const getDataSource = () => {
		printTemplateService
			.getDatasource()
			.then((res) => {
				setDataSourceList(res);
			})
			.catch((error) => {
				console.error(error);
				toast.error("获取模板数据源失败！");
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (printTemplate: PrintTemplate) => {
		setEditingData(printTemplate);

		const file = {
			uid: "1",
			name: printTemplate.templateFileName,
			status: "done",
			// 如果是图片，可以转成 Data URL 显示缩略图
			thumbUrl: `data:image/png;base64,${printTemplate.templateFile}`,
		};
		setFileList([file]);

		form.setFieldsValue(printTemplate);
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (printTemplate: PrintTemplate) => {
		setEditingData(printTemplate);

		const file = {
			uid: "1",
			name: printTemplate.templateFileName,
			status: "done",
			// 如果是图片，可以转成 Data URL 显示缩略图
			thumbUrl: `data:image/png;base64,${printTemplate.templateFile}`,
		};
		setFileList([file]);

		form.setFieldsValue(printTemplate);
		setIsView(true);
		setDrawerVisible(true);
	};

	const handleDesign = async (printTemplate: PrintTemplate) => {
		if (!printTemplate.id) {
			toast.error("模板ID不能为空");
			return;
		}
		setSubmitTip("设计中...");
		setSubmitLoading(true);
		await printTemplateService
			.design(printTemplate.id)
			.then((res) => {
				const clientData: PrintResponse = res;
				console.log(res);
				if (clientData.type === "hiprint") {
					// TODO 打开一个新的tab页签
					navigate("/tool/hiprint", {
						state: {
							templateId: printTemplate.id,
						},
					});
				} else if (clientData.type === "btw" || clientData.type === "lpt") {
					clientData.design = true;
					if (clientData.template) {
						const protocol = window.location.protocol;
						const hostname = window.location.hostname;
						const requestUrl = `${protocol}//${hostname}:8001`;

						clientData.template = `${requestUrl}${clientData.template}`;
					}

					let ws = new WebSocket("ws://localhost:8086/ws");

					ws.onopen = () => {
						console.log("ws请求数据", JSON.stringify(clientData));
						ws.send(JSON.stringify(clientData));
					};

					ws.onmessage = () => {
						ws.close();
					};

					ws.onclose = () => {
						console.log("关闭WebSocket连接！");
					};

					ws.onerror = (evt) => {
						console.log(evt);
						toast.error("打印服务调用失败");
					};
				}
			})
			.catch((error) => {
				console.error(error);
				toast.error("加载打印模板失败！");
			})
			.finally(() => {
				setSubmitLoading(false);
			});
	};

	// 提交表单数据
	const handleSubmit = async (values: PrintTemplate) => {
		const data: any = {
			...values,
			id: editingData?.id,
		};

		// 新增或重新上传时才处理文件
		if (fileList.length > 0 && fileList[0].originFileObj) {
			const file = fileList[0].originFileObj;
			const reader = new FileReader();

			reader.onload = async (e) => {
				const fileData = e.target.result;
				data.templateFile = Array.from(new Uint8Array(fileData));
				await doSubmit(data);
			};
			reader.onerror = () => {
				toast.error("文件读取失败");
			};
			reader.readAsArrayBuffer(file);
			return; // 异步处理，后续逻辑在 reader.onload
		}

		if (form.getFieldValue("type") !== "hiprint") {
			if (editingData && editingData.templateFile) {
				// 编辑时未上传新文件，直接用原有数据
				data.templateFile = editingData.templateFile;
				await doSubmit(data);
				return;
			} else {
				// 没有文件数据，提示用户上传
				toast.error("请上传模板文件");
				return;
			}
		} else {
			// 如果是 hiprint 模板，直接提交数据
			await doSubmit(data);
		}
	};

	// 抽出实际提交逻辑
	const doSubmit = async (data: any) => {
		try {
			setSubmitLoading(true);
			setSubmitTip("数据提交中...");
			if (editingData) {
				await printTemplateService.update(data);
				toast.success("更新标签打印模板成功");
			} else {
				await printTemplateService.add(data);
				toast.success("创建标签打印模板成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error: any) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setSubmitLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		form.setFieldValue("isDefault", "1");
		form.setFieldValue("enableFlag", "1");
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await printTemplateService.remove(selectedRowKeys);
			toast.success("删除标签打印模板成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const showCustomerSelect = () => {
		setCustomerSelectVisible(true);
	};

	const handleCustomerSelected = (customer: any) => {
		form.setFieldsValue({
			clientName: customer.client_name,
			clientId: customer.id,
		});
		setCustomerSelectVisible(false);
	};

	const openSelectMaterial = (id: React.Key) => {
		setSelectMaterialVisiable(true);
	};

	const handleSelectMaterial = (material: any) => {
		setSelectMaterialVisiable(false);
		if (material) {
			const { id, materialCode, materialName } = material;
			form.setFieldsValue({
				materialId: id,
				materialCode: materialCode,
				materialName: materialName,
			});
		}
	};

	// 上传前检查
	const beforeUpload = (file: File) => {
		// 这里可以添加文件类型、大小等检查
		const isLt10M = file.size / 1024 / 1024 < 10;
		if (!isLt10M) {
			toast.error("文件必须小于10MB!");
			return AntdUpload.LIST_IGNORE;
		}
		return true;
	};

	// 处理文件列表变化
	const handleFileListChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
		if (newFileList.length === 0) {
			form.setFieldValue("fileName", "");
			setFileList([]);
			return;
		}
		const file = newFileList[0];
		form.setFieldValue("templateFileName", file.name);
		setFileList(newFileList);
	};

	return (
		<Spin spinning={submitLoading} tip={submitTip} size="large">
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="name" label="名称">
						<Input placeholder="请输入名称" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<CustomTable
					loading={loading}
					columnsConfig={columns}
					dataSource={list}
					total={total}
					selectedRowKeys={selectedRowKeys}
					setSelectedRowKeys={setSelectedRowKeys}
					current={queryParams.page}
					pageSize={queryParams.pageSize}
					onRefresh={fetchPageList}
					onPageChange={handlePageChange}
					selectable
					toolbarButtons={
						<>
							<Button type="primary" onClick={handleAdd}>
								新增
							</Button>
							<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
								删除
							</Button>
						</>
					}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑标签打印模板" : "新增标签打印模板"}
				width={600}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item
						name="name"
						label="名称"
						rules={[
							{
								required: true,
								message: "请填写名称",
							},
						]}
					>
						<Input placeholder="请输入名称" allowClear />
					</Form.Item>

					<Form.Item name="type" label="模板类型">
						<Select options={typeOptions} allowClear />
					</Form.Item>

					<Form.Item name="materialId" label="物料ID" hidden>
						<Input />
					</Form.Item>
					<Form.Item label="物料编码" name="materialCode" rules={[{ required: true, message: "请选择物料编码" }]}>
						<Input.Search
							placeholder="请选择物料"
							allowClear
							enterButton={<ExportOutlined />}
							onSearch={openSelectMaterial}
						/>
					</Form.Item>
					<Form.Item name="materialName" label="物料名称">
						<Input disabled />
					</Form.Item>

					<Form.Item name="clientId" label="客户" hidden>
						<Input placeholder="请输入客户" allowClear />
					</Form.Item>
					<Form.Item name="clientName" label="客户">
						<Input.Search
							placeholder="请输入客户"
							allowClear
							enterButton={<UserAddOutlined />}
							onSearch={showCustomerSelect}
						/>
					</Form.Item>

					{/* 仅当 type !== 'hiprint' 时显示模板文件上传和文件名输入 */}
					{form.getFieldValue("type") !== "hiprint" && (
						<>
							<Form.Item name="templateFile" label="模板文件">
								<Upload
									maxCount={1}
									beforeUpload={beforeUpload}
									onChange={handleFileListChange}
									fileList={fileList}
									multiple={false}
									thumbnail={false}
								/>
							</Form.Item>

							<Form.Item name="templateFileName" label="模板文件名称">
								<Input placeholder="请输入模板文件名称" allowClear />
							</Form.Item>
						</>
					)}

					<Form.Item name="dataSource" label="数据源">
						<Select
							options={dataSourceList.map((item) => ({
								label: item.name,
								value: item.value,
							}))}
						/>
					</Form.Item>

					<Form.Item
						name="isDefault"
						label="是否默认"
						valuePropName="checked"
						normalize={(value) => value === 1}
						getValueFromEvent={(checked) => (checked ? 1 : 0)}
					>
						<Switch checkedChildren="是" unCheckedChildren="否" disabled={isView} />
					</Form.Item>

					<Form.Item
						name="enableFlag"
						label="启用状态"
						valuePropName="checked"
						normalize={(value) => value === 1}
						getValueFromEvent={(checked) => (checked ? 1 : 0)}
					>
						<Switch checkedChildren="启用" unCheckedChildren="停用" disabled={isView} />
					</Form.Item>

					<Form.Item name="remark" label="备注">
						<Input.TextArea />
					</Form.Item>
				</Form>
			</Drawer>

			{/* 客户选择器 */}
			<SingleCustomerSelector
				open={customerSelectVisible}
				onCancel={() => setCustomerSelectVisible(false)}
				onOk={(item) => handleCustomerSelected(item)}
			/>

			{/* 物料选择器 */}
			<SingleMaterialSelector
				open={selectMaterialVisiable}
				onCancel={() => setSelectMaterialVisiable(false)}
				onOk={(item) => handleSelectMaterial(item)}
			/>
		</Spin>
	);
}
